package dk.controller;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ReturnData.ResponseData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.hutool.core.lang.UUID;
import dk.Service.TokenService;
import dk.beans.Student;
import dk.mapper.StudentMapper;

@RestController
public class H5StudentController {
@Autowired
StudentMapper studentmapper;
@Autowired
TokenService tokenservice;
@PostMapping("StuLogin")
public ResponseData StuLogin(String phone,String code,String UUidcode,String password) {
	ResponseData data = new ResponseData();
	int count  = Math.toIntExact(studentmapper.selectCount(new QueryWrapper<Student>().eq("phone", phone)));
	if(count == 0) {
		//判断为新用户 分配uuid
		String username = UUID.randomUUID().toString().replace("-", "");;
		Student newstu = new Student();
		newstu.setUsername(username);
		newstu.setPhone(phone);
		newstu.setPassword(password);
		newstu.setLastlogintime(new Date());
		newstu.setIslocked(0);
		newstu.setExamcount(0);
		newstu.setErrcount(0);
		studentmapper.insert(newstu);
		data.setData(newstu.getId());
	    data.setMessage("注册成功");
	    data.setCode(200);
	    return data;
				
	}
	if(tokenservice.CheckCheckUUidAndCode(UUidcode,code) != 1) {
		data.setCode(201);
		data.setMessage("验证码错误");
		return data;
	}
	Student student = new Student();
	student = studentmapper.selectOne(new QueryWrapper<Student>().eq("phone",phone));
	if(!student.getPassword().equals(password)) {
		data.setCode(201);
		data.setMessage("密码错误");
		return data;
	}
	if(student.getIslocked() != 0) {
		data.setCode(201);
		data.setMessage("用户已被锁定,请联系管理");
		return data;
	}
    data.setData(student.getId());
    data.setMessage("登录成功");
    data.setCode(200);
    //登录成功更新登录时间
    student.setLastlogintime(new Date());
    //根据电话更新
    studentmapper.update(student, new QueryWrapper<Student>().eq("phone",phone));
    
	return data;
}
@PostMapping("StuChangePassword")
public ResponseData StuChangePassword(String oldpassword,String newpassword,Integer id) {
	ResponseData data = new ResponseData();
	//根据id查询出正确密码
	Student student = studentmapper.selectOne(new QueryWrapper<Student>().eq("id",id));
	if(student.getPassword().equals(oldpassword)) {
		//比对成功
		student.setPassword(newpassword);
		studentmapper.update(student,new QueryWrapper<Student>().eq("id",id));
		data.setCode(200);
		data.setMessage("密码更新成功");
	}
	else {
		data.setCode(201);
		data.setMessage("更新失败,请输入正确得原密码");
	}
	return data;
}

}
